<?php

	require_once(dirname(dirname(dirname(dirname(__FILE__)))) . "/engine/start.php");
	gatekeeper();
	
	$chatsessions = (array)get_entities_from_relationship( "elggchat_session_member",get_loggedin_userid(), true, null,null,null,"guid");
	$invitations = (array)get_entities_from_relationship( "elggchat_session_member_invite",get_loggedin_userid(), true);
	
	$chatsessions = array_merge($chatsessions, $invitations);
	echo "<div id='elggchat_sessions'>";
	
	foreach($chatsessions as $session){
		$sessionName = "";
		if($session->guid){
		
			$maxmembers = get_entities_from_relationship("elggchat_session_member", $session->guid, null, null, null, null, null, null, null, true);
			$members = get_entities_from_relationship("elggchat_session_member", $session->guid, null, null, null, null, null, $maxmembers);
	
			$maxinvites = get_entities_from_relationship("elggchat_session_member_invite", $session->guid, null, null, null, null, null, null, null, true);
			$invites = get_entities_from_relationship("elggchat_session_member_invite", $session->guid, null, null, null, null, null, $maxinvites);
					
			foreach($invites as $invite){
				if($invite->guid == get_loggedin_userid()){
					$sessionName = "Invited Session (";
					
					foreach($members as $member){
						if($member->guid != get_loggedin_userid()){
							$sessionName .= " " . $member->name;
						}
					}
					if(strlen($sessionName) > 50){
						$sessionName = substr($sessionName,0,50) . "..)";
					} else {
						$sessionName .= ")";
					}
					
				}
			}
			
			if(!$sessionName){
				foreach($members as $member){
					
					if($member->guid != get_loggedin_userid()){
						$sessionName .= " " . $member->name;
					}
					
				}
				if($sessionName){
					$sessionName = "Session with (" . $sessionName;
					if(strlen($sessionName) > 50){
						$sessionName = substr($sessionName,0,50) . "..)";
					} else {
						$sessionName .= ")";
					}
				}
			}
			
			if(!$sessionName) {
				$sessionName = "Chatsession with no buddy's";
			}
			
			echo "<div class='elggchat_session' rel='" . $session->guid . "' onclick='javascript:joinSession(" . $session->guid . ")'>" . $sessionName . "</div>";
		}
	}

	$numOnline = 0;
	$maxfriends = get_entities_from_relationship("friend", get_loggedin_userid(), null, null, null, null, null, null, null, true);
	$friends = get_entities_from_relationship("friend", get_loggedin_userid(), null, null, null, null, null, $maxfriends);
	foreach($friends as $friend){
		if(time() - $friend->last_action < 600){
			$numOnline++;
		}
	}
	
	echo "
			</div>
			<div id='elggchat_friends'>
				<a href='javascript:toggleFriendsPicker();'>" . elgg_echo("friends") . " (" . $numOnline . " online)</a>
			</div>";	
	exit();
?>
